package com.rlax.framework.plugin.shiro;

import java.io.Serializable;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.redis.Redis;

/***
 * 用redis 实现 分布式缓存
 * 
 * @author Rlax
 * 
 */
public class SessionDAO extends EnterpriseCacheSessionDAO {

	private static final Logger logger = LoggerFactory.getLogger(SessionDAO.class);
	
	public static SessionDAO me;

	@Override
	public void setCacheManager(CacheManager cacheManager) {
		super.setCacheManager(cacheManager);

		me = this;
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionid = super.doCreate(session);
		Redis.use().set(sessionid, session);
		logger.debug("创建session {} name {}", sessionid, session.getClass().getName());
		return sessionid;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
        // 先获取 ehcache，如果没有在获取 redis
        Session session = super.doReadSession(sessionId); 
        if(session == null){
        	session = Redis.use().get(sessionId);
        	if (session == null) {
        		logger.debug("读取session {} 已经失效", sessionId);
        	} else {
        		logger.debug("读取session {} name {}", session.getId(), session.getClass().getName());
        	}
        }
        return session;
	}

	@Override
	protected void doUpdate(Session session) {
		super.doUpdate(session);
		Redis.use().set(session.getId(), session);
		logger.debug("更新session {} name {}", session.getId(), session.getClass().getName());
	}

	@Override
	protected void doDelete(Session session) {
		super.doDelete(session);
		Redis.use().del(session.getId());
		logger.debug("删除session {} name {}", session.getId(), session.getClass().getName());
	}

}
